public class Test {
    //二分查找
    public int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while(left <= right){
            int mid = left + (right - left) / 2;
            if(target > nums[mid]) left = mid + 1;
            else if(target < nums[mid]) right = mid - 1;
            else return mid;
        }
        return -1;
    }
    //在排序数组中查找第一个和最后一个元素位置（细节题）
    public int[] searchRange(int[] nums, int target) {
        int[] array = new int[2];
        array[0] = array[1] = -1;
        //判断nums长度为0
        if(nums.length == 0) return array;
        int left = 0, right =  nums.length - 1;
        //找左端点
        while(left < right){
            int mid = left + (right - left) / 2;
            if(nums[mid] < target) left = mid + 1;
            else right = mid;
        }
        if(nums[left] != target) return array;
        else array[0] = left;
        left = 0;right = nums.length - 1;
        //找右端点
        while(left < right){
            int mid = left + (right - left + 1) / 2;
            if(nums[mid] <= target) left = mid;
            else right = mid - 1;
        }
        array[1] = left;
        return array;
    }
}
